package com.jlzj.registrar;

import com.jlzj.annotation.MyMapperScan;
import com.jlzj.factorybean.MyFactoryBean;
import com.jlzj.scanner.MyClassScanner;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * TODO:
 *
 * @author jiangyangchuan
 * @date 2022/8/14 0014 17:05
 */

public class MyBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        ImportBeanDefinitionRegistrar.super.registerBeanDefinitions(importingClassMetadata, registry);
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(MyMapperScan.class.getName());
        String packagePath = (String)annotationAttributes.get("value");
        if(StringUtils.hasLength(packagePath)){
            try {
                List<Class> classList = MyClassScanner.doScan(packagePath);
                for(Class clazz : classList){
                    AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
                    beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(clazz);
                    beanDefinition.setBeanClass(MyFactoryBean.class);
                    registry.registerBeanDefinition(clazz.getName(),beanDefinition);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
